<template>
  <div class="risk-rule-form-page">
    <el-card>
      <div class="form-header">
        <h2>{{ formTitle }}</h2>
        <el-button type="primary" @click="goBack">返回列表</el-button>
      </div>

      <el-form
        :model="formData"
        :rules="formRules"
        ref="formRef"
        label-width="120px"
        class="form-content"
      >
        <el-form-item label="规则名称" prop="ruleName">
          <el-input
            v-model="formData.ruleName"
            placeholder="请输入规则名称"
            maxlength="50"
            show-word-limit
          />
        </el-form-item>

        <el-form-item label="规则类型" prop="ruleType">
          <el-select v-model="formData.ruleType" placeholder="请选择规则类型">
            <el-option label="IP限制规则" :value="1" />
            <el-option label="用户行为规则" :value="2" />
            <el-option label="内容过滤规则" :value="3" />
            <el-option label="频率限制规则" :value="4" />
          </el-select>
        </el-form-item>

        <!-- 规则限制字段将在后续开发中实现 -->

        <el-form-item label="状态" prop="status">
          <el-radio-group v-model="formData.status">
            <el-radio :label="1">启用</el-radio>
            <el-radio :label="0">停用</el-radio>
          </el-radio-group>
        </el-form-item>



        <el-form-item>
          <el-button type="primary" @click="submitForm" :loading="loading">提交</el-button>
          <el-button @click="resetForm">重置</el-button>
          <el-button @click="goBack">取消</el-button>
        </el-form-item>
      </el-form>
    </el-card>
  </div>
</template>

<script setup lang="ts">
  import { ref, onMounted, reactive, computed } from 'vue'
  import { useRoute, useRouter } from 'vue-router'
  import { ElMessage, ElMessageBox, type FormInstance, type FormRules } from 'element-plus'
  import { saveRiskRule, updateRiskRule, getRiskRuleDetail } from '@/api/riskApi'
  import type {
    RiskRuleSaveParam,
    RiskRuleUpdateParam,
    RiskRule
  } from '@/api/model/riskModel'
  import { ApiStatus } from '@/utils/http/status'

  const route = useRoute()
  const router = useRouter()

  const formRef = ref<FormInstance>()
  const loading = ref(false)
  const isEdit = ref(false)
  const ruleId = ref<string>('')

  const formData = ref<RiskRuleSaveParam | RiskRuleUpdateParam>({
    ruleName: '',
    ruleType: 1,
    status: 1,
    rulePlaceOrderLimit: '',
    ruleWaitPayLimit: '',
    ruleSkuLimit: '',
    rulePostSaleLimit: '',
    ruleSwitchPostSale: 0,
    ruleSwitchSku: 0,
    ruleSwitchPlaceOrder: 0,
    ruleSwitchWaitPay: 0
  })

  const formRules = reactive<FormRules>({
    ruleName: [
      { required: true, message: '请输入规则名称', trigger: 'blur' },
      { min: 2, max: 50, message: '长度在 2 到 50 个字符', trigger: 'blur' }
    ],
    ruleType: [
      { required: true, message: '请选择规则类型', trigger: 'change' }
    ],
    status: [
      { required: true, message: '请选择状态', trigger: 'change' }
    ]
  })

  const formTitle = computed(() => {
    return isEdit.value ? '编辑风险规则' : '新增风险规则'
  })

  onMounted(() => {
    initForm()
  })

  function initForm() {
    const { id } = route.params
    if (id && typeof id === 'string') {
      isEdit.value = true
      ruleId.value = id
      loadRuleDetail(id)
    } else {
      isEdit.value = false
      resetForm()
    }
  }

  // 加载规则详情
  async function loadRuleDetail(id: string) {
    try {
      loading.value = true
      const res = await getRiskRuleDetail({ id: id })
      if (res.code === ApiStatus.success && res.data) {
        const detail = res.data
        formData.value = {
          id: detail.id,
          ruleName: detail.ruleName || '',
          ruleType: detail.ruleType || 1,
          status: detail.status || 1,
          rulePlaceOrderLimit: detail.rulePlaceOrderLimit || '',
          ruleWaitPayLimit: detail.ruleWaitPayLimit || '',
          ruleSkuLimit: detail.ruleSkuLimit || '',
          rulePostSaleLimit: detail.rulePostSaleLimit || '',
          ruleSwitchPostSale: detail.ruleSwitchPostSale || 0,
          ruleSwitchSku: detail.ruleSwitchSku || 0,
          ruleSwitchPlaceOrder: detail.ruleSwitchPlaceOrder || 0,
          ruleSwitchWaitPay: detail.ruleSwitchWaitPay || 0
        }
      } else {
        ElMessage.error('获取规则详情失败')
        goBack()
      }
    } catch (error) {
      console.error('获取规则详情失败:', error)
      ElMessage.error('获取规则详情失败')
      goBack()
    } finally {
      loading.value = false
    }
  }

  // 提交表单
  async function submitForm() {
    if (!formRef.value) return

    try {
      await formRef.value.validate()
      loading.value = true



      if (isEdit.value) {
        const updateParam: RiskRuleUpdateParam = {
          id: Number(ruleId.value),
          ruleName: formData.value.ruleName!,
          ruleType: formData.value.ruleType!,
          status: formData.value.status!,
          rulePlaceOrderLimit: formData.value.rulePlaceOrderLimit,
          ruleWaitPayLimit: formData.value.ruleWaitPayLimit,
          ruleSkuLimit: formData.value.ruleSkuLimit,
          rulePostSaleLimit: formData.value.rulePostSaleLimit,
          ruleSwitchPostSale: formData.value.ruleSwitchPostSale,
          ruleSwitchSku: formData.value.ruleSwitchSku,
          ruleSwitchPlaceOrder: formData.value.ruleSwitchPlaceOrder,
          ruleSwitchWaitPay: formData.value.ruleSwitchWaitPay
        }
        const res = await updateRiskRule(updateParam)
        if (res.code === ApiStatus.success) {
          ElMessage.success('更新成功')
          goBack()
        } else {
          ElMessage.error(res.message || '更新失败')
        }
      } else {
        const saveParam: RiskRuleSaveParam = {
          ruleName: formData.value.ruleName!,
          ruleType: formData.value.ruleType!,
          status: formData.value.status!,
          rulePlaceOrderLimit: formData.value.rulePlaceOrderLimit,
          ruleWaitPayLimit: formData.value.ruleWaitPayLimit,
          ruleSkuLimit: formData.value.ruleSkuLimit,
          rulePostSaleLimit: formData.value.rulePostSaleLimit,
          ruleSwitchPostSale: formData.value.ruleSwitchPostSale,
          ruleSwitchSku: formData.value.ruleSwitchSku,
          ruleSwitchPlaceOrder: formData.value.ruleSwitchPlaceOrder,
          ruleSwitchWaitPay: formData.value.ruleSwitchWaitPay
        }
        const res = await saveRiskRule(saveParam)
        if (res.code === ApiStatus.success) {
          ElMessage.success('新增成功')
          goBack()
        } else {
          ElMessage.error(res.message || '新增失败')
        }
      }
    } catch (error) {
      console.error('提交表单失败:', error)
    } finally {
      loading.value = false
    }
  }

  // 重置表单
  function resetForm() {
    if (formRef.value) {
      formRef.value.resetFields()
      formData.value = {
        ruleName: '',
        ruleType: 1,
        status: 1,
        rulePlaceOrderLimit: '',
        ruleWaitPayLimit: '',
        ruleSkuLimit: '',
        rulePostSaleLimit: '',
        ruleSwitchPostSale: 0,
        ruleSwitchSku: 0,
        ruleSwitchPlaceOrder: 0,
        ruleSwitchWaitPay: 0
      }
    }
  }

  // 返回列表
  function goBack() {
    router.push('/risk/riskRules')
  }
</script>

<style lang="scss" scoped>
  .risk-rule-form-page {
    padding: 20px;

    .form-header {
      display: flex;
      justify-content: space-between;
      align-items: center;
      margin-bottom: 30px;
      padding-bottom: 15px;
      border-bottom: 1px solid #eee;

      h2 {
        margin: 0;
        color: #303133;
        font-size: 20px;
        font-weight: 500;
      }
    }

    .form-content {
      max-width: 800px;
      margin: 0 auto;

      .priority-tip {
        margin-left: 10px;
        color: #909399;
        font-size: 12px;
      }

      .el-form-item {
        margin-bottom: 22px;
      }

      .el-input,
      .el-select,
      .el-textarea,
      .el-date-editor {
        width: 100%;
      }
    }

    // 响应式设计
    @media screen and (max-width: $device-phone) {
      padding: 10px;

      .form-header {
        flex-direction: column;
        align-items: flex-start;
        gap: 15px;

        h2 {
          font-size: 18px;
        }
      }

      .form-content {
        .el-form-item {
          :deep(.el-form-item__label) {
            width: 100% !important;
            text-align: left;
          }

          :deep(.el-form-item__content) {
            margin-left: 0 !important;
          }
        }
      }
    }
  }
</style>